<template>
    <div class="editor-page" v-resize="editorResize">
        <editorHeader ref="editorHeaderRef" @handleClick="doAction" v-model:docInfo="docInfo" :activeName="activeName"
            @close="handleClose" :showWrit="showWrit" @otherAction="otherAction" :saveTime="saveTime" :showLately="true"
            :coorList="coorList" :showBack="!isTemplate" :knowledgeType="knowledgeType"
            @changeEditStatus="changeEditStatus">
            <slot>
                <div class="no-editor-mark" v-if="bodyLoading"></div>
            </slot>
        </editorHeader>
        <div class="ediotr-body" v-loading="bodyLoading" v-if="docInfo.type"
            :style="!['document_flow', 'md'].includes(docInfo.type) ? { 'aspect-ratio': 16/9 } : {}">
            <div class="editor-content" id="editor-content" :style="{ width: getEditorWidth(), minWidth: getEditorWidth() }">
                <AomaoEditor ref="editorRef" :id="docId" @renderFinish="renderFinish" :isTemplate="isTemplate"
                    :docInfo="docInfo" @changeLatelySave="changeLatelySave" v-if="docInfo.type === 'document_html'">
                </AomaoEditor>
                <LuckySheet ref="editorRef" :id="docId" :isTemplate="isTemplate" @renderFinish="renderFinish"
                    @changeLatelySave="changeLatelySave" :isEdit="true" :docInfo="docInfo"
                    v-if="docInfo.type === 'document_xlsx'"></LuckySheet>
                <EditorMd ref="editorRef" v-else-if="docInfo.type === 'md'" :id="docId" :docInfo="docInfo"
                    @renderFinish="renderFinish" @changeLatelySave="changeLatelySave"></EditorMd>
                <XmindMap ref="editorRef" v-else-if="docInfo.type === 'xmind'" :id="docId" :docInfo="docInfo"
                    @renderFinish="renderFinish" @changeLatelySave="changeLatelySave"
                    :isReadOnly="activeName == 'version'"></XmindMap>
                <MindElixir ref="editorRef" v-else-if="docInfo.type === 'document_map'" :docInfo="docInfo" :id="docId"
                    @renderFinish="renderFinish" @changeLatelySave="changeLatelySave"></MindElixir>
                <Topology ref="editorRef" v-else-if="docInfo.type === 'document_flow'" :docInfo="docInfo" :id="docId"
                    @renderFinish="renderFinish" @changeLatelySave="changeLatelySave"></Topology>
            </div>
            <writing v-if="activeName == 'writ'" @close="handleClose" :isShowArrow="isShowArrow" :show="!showButton"
                @changeArrow="changeArrow" :searchVal="searchVal"></writing>
            <version :docId="docId" v-if="activeName == 'version'" @close="handleClose" :isShowArrow="isShowArrow"
                :show="!showButton" @changeArrow="changeArrow" @endSwitchVersion="endSwitchVersion"></version>
            <div class="fixed-button" v-if="activeName != 'writ' && isShowArrow && showButton" @click="openArrow">
                <svg class="fixed-icon">
                    <use v-bind:xlink:href="`#${activeName == 'writ' ? 'keowledge-a-zu7070' : 'keowledge-a-zu7071'}`"></use>
                </svg>
            </div>
        </div>
        <selectKnow ref="selectKnowRef" :title="$t('message.text.moveTitle')" @callBack="getCheckedFile"
            @close="handleClose"></selectKnow>
    </div>
</template>
<script setup lang="ts">
import {
    ref, watch, onMounted, nextTick, onBeforeUnmount, getCurrentInstance, defineAsyncComponent
} from 'vue'
import type { ComponentInternalInstance } from 'vue'
import { useRoute } from "vue-router"
import { getInfo } from '@/api/common'
import { getTemplateInfo } from '@/api/template'
import editorHeader from './editorHeader.vue'

// import aomaoEditor from '@/components/aomaoEditor/index.vue'
const AomaoEditor = defineAsyncComponent(() => import('@/components/aomaoEditor/index.vue'))

// import luckySheet from '@/components/luckySheet/index.vue'
const LuckySheet = defineAsyncComponent(() => import('@/components/luckySheet/index.vue'))

// import editorMd from '@/components/editorMd/index.vue'
const EditorMd = defineAsyncComponent(() => import('@/components/editorMd/index.vue'))

// import xmindMap from '@/components/xmind-map/index.vue'
const XmindMap = defineAsyncComponent(() => import('@/components/xmind-map/index.vue'))

// import mindElixir from '@/components/mindElixir/index.vue'
const MindElixir = defineAsyncComponent(() => import('@/components/mindElixir/index.vue'))

// import topology from '@/components/topology/index.vue'
const Topology = defineAsyncComponent(() => import('@/components/topology/index.vue'))

import selectKnow from '@/views/selectKnow/index.vue'
import writing from '@/views/common/writing.vue'
import version from '@/views/common/version.vue'
import { setStore, getStore } from '@/utils/store'
import { locationOther } from '@/api/knowledge'
import useSocketStore from '@/store/socket'
import useUserInfoStore from '@/store/userInfo'
import { socketStatus } from '@/const/socketStatus'

import * as O from '@/utils/uniqueId'
import { useHookI18n } from '@/hooks/i18n'
const { $t } = useHookI18n()

const socketStore = useSocketStore()
const userStore = useUserInfoStore()

const route = useRoute()
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const editorHeaderRef = ref()
const bodyLoading = ref(true)
const isTemplate = ref(false)
const docId = ref('')
const knowId = ref('')
const docInfo = ref<any>({})
const editorRef = ref()
const selectKnowRef = ref()
const activeName = ref('')
const showWrit = ref(false)
const isShowArrow = ref(false)
const showButton = ref(false)
const editorWidth = ref(0)
const saveTime = ref('')
const coorList = ref([])
const knowledgeType = ref(0)
const searchVal = ref('')

const props = defineProps({
    docId: {
        type: String,
        default: ''
    },
    knowId: {
        type: String,
        default: ''
    },
    type: {
        type: String,
        default: ''
    }
})

let uniId = ''
const start = () => {
    isTemplate.value = props.type === 'template'
    docId.value = props.docId
    knowId.value = props.knowId
    if (route.query.fromId) {
        knowledgeType.value = route.params.type == 'my' ? 1 : 0
    }
    uniId = O.uniqueId(knowledgeType.value == 0 ? 'all' : 'my' + '-' + knowId.value + '-' + docId.value)
    init()
}
onMounted(() => {
    start()
    
    document.addEventListener('keydown', handleEvent)
    // 关闭当前页面的时候需要删除一次记录
    window.addEventListener('unload', handleUnload)
    proxy.$eventBus.$on('openWrit', openWrit)
})
watch(() => props.docId, () => {
    nextTick(() => {
        start()
    })
})
function handleUnload() {
    let backUrlList = getStore({ name: 'backPageList', reqEnc: true })
    if (backUrlList[uniId]) {
        if (backUrlList[uniId].num <= 0) {
            delete backUrlList[uniId]
        } else {
            backUrlList[uniId].num -= 1
            if (backUrlList[uniId].num <= 0) {
                backUrlList[uniId].num = 0
            }
        }
        setStore({ name: 'backPageList', content: backUrlList, reqEnc: true })
    }
}
onBeforeUnmount(() => {
    proxy.$eventBus.$off('openWrit', openWrit)
    document.removeEventListener("keydown", handleEvent)
})
watch(() => socketStore.socketMsg, (newV, oldV) => {
    const command = (socketStatus[newV.command] || newV.command) + ''
    switch (command) {
        case '6':
            if (['document_xlsx', 'md'].indexOf(docInfo.value.type) != -1) {
                socketStore.SEND_MESSAGE({
                    cmd: 19,
                    messageType: 4,
                    userId: userStore.userInfo.id,
                    businessId: docId.value + '-knowledge-ui',
                })
                socketStore.SEND_MESSAGE({
                    cmd: 19,
                    messageType: 4,
                    userId: userStore.userInfo.id,
                    businessId: docId.value + '-user-list'
                })
            }
            socketStore.SEND_MESSAGE({
                cmd: 25,
                from: userStore.userInfo.id,
                businessId: docId.value + '-knowledge-ui',
                expire: 60 * 60
            })
            socketStore.SEND_MESSAGE({
                cmd: 7,
                groupType: 1,
                groupId: docId.value + '-knowledge-ui',
            })
            socketStore.SEND_MESSAGE({
                cmd: 31,
                groupId: docId.value + '-knowledge-ui',
            })
            break;
        case '9':
            if (newV.data && newV.data.user) {
                let index = hasInGroup(newV.data.user.userId)
                if (index == -1 && newV.data.user.status == 'online') {
                    coorList.value.push(newV.data.user)
                } else {
                    if (index > -1 && newV.data.user.status == 'offline') {
                        coorList.value.splice(index, 1)
                    }
                }
            }
            break
        case '10':
            if (newV.data && newV.data.user) {
                let index = hasInGroup(newV.data.user.userId)
                if (index > -1) {
                    coorList.value.splice(index, 1)
                }
            }
            break
        case '32':
            if (newV.data) {
                for (let u of newV.data.users) {
                    let ix = hasInGroup(u.userId)
                    if (ix == -1) {
                        if (u.status == 'online') {
                            coorList.value.push(u)
                        }
                    } else {
                        if (u.status == 'offline') {
                            coorList.value.splice(ix, 1)
                        }
                    }
                }
            }
            break
        default:
            break;
    }
})
// 判断人员是否已加入群组
function hasInGroup(userId: any) {
    let index = -1
    for (let o in coorList.value) {
        if (coorList.value[o].userId == userId) {
            index = o
        }
    }
    return index
}
function editorResize({ width }) {
    editorWidth.value = width
    if (activeName.value) {
        if (activeName.value == 'version') {
            if (docInfo.value.type == 'xmind') {
                isShowArrow.value = editorWidth.value - 1160 < 240
            } else {
                isShowArrow.value = editorWidth.value - 980 < 240
            }
        } else if (activeName.value == 'writ') {
            if (docInfo.value.type == 'xmind') {
                isShowArrow.value = editorWidth.value - 1160 < 500
            } else {
                isShowArrow.value = editorWidth.value - 980 < 500
            }
        }
        if (!isShowArrow.value) {
            showButton.value = false
        }
    }
}
function getEditorWidth() {
    let str = '100%'
    if (activeName.value == 'writ' && !isShowArrow.value) {
        if (docInfo.value.type == 'xmind') {
            str = '1160px'
        } else {
            str = '980px'
        }
    }
    if (activeName.value == 'version' && !isShowArrow.value) {
        str = 'calc(100% - 240px)'
    }
    nextTick(() => {
        if (!bodyLoading.value && docInfo.value.type == 'document_xlsx') {
            editorRef.value?.handleResize()
        }
    })
    return str
}
function init() {
    if (docId.value) {
        let fun = getInfo
        if (isTemplate.value) {
            fun = getTemplateInfo
        }
        fun(docId.value).then(res => {
            if (res.data.code == 0) {
                docInfo.value = res.data.data
                showWrit.value = ['document_html'].indexOf(docInfo.value.type) == -1
                // ['document_html','document_xlsx','md','document_flow'].indexOf(docInfo.value.type)!=-1 &&
                if (userStore.access_token && !isTemplate) {
                    socketStore.INIT(docId.value)
                }
            }
        })
    }
}
function doAction(val: { value: any; searchText?: string }) {
    isShowArrow.value = false
    showButton.value = false
    if (activeName.value == val.value) {
        activeName.value = ''
        editorRef.value?.changeEditStatus(false)
    } else {
        // 是否恢复布局，主要对于版本
        let reLayout = false
        if (activeName.value == 'version') {
            reLayout = true
        }
        switch (val.value) {
            case 'move':
                activeName.value = val.value
                selectKnowRef.value.init()
                break;
            case 'version':
                activeName.value = val.value
                if (docInfo.value.type == 'xmind') {
                    isShowArrow.value = editorWidth.value - 1160 < 240
                } else {
                    isShowArrow.value = editorWidth.value - 980 < 240
                }
                editorRef.value?.changeEditStatus(true)
                break
            case 'writ':
                openWrit(val)
                break
            default:
                break;
        }
        if (reLayout) {
            editorRef.value?.changeEditStatus(false)
        }
    }
}
function openWrit(val: { searchText: string; value: string }) {
    searchVal.value = val.searchText || ''
    if (activeName.value != val.value) {
        let reLayout = false
        if (activeName.value == 'version') {
            reLayout = true
        }
        activeName.value = val.value
        if (docInfo.value.type == 'xmind') {
            isShowArrow.value = editorWidth.value - 1160 < 500
        } else {
            isShowArrow.value = editorWidth.value - 980 < 500
        }
        try {
            editorRef.value?.specMenuStatus(false)
        } catch (error) {

        }
        if (reLayout) {
            editorRef.value?.changeEditStatus(false)
        }
    }
}
function otherAction(val: any) {
    switch (val) {
        case 'save':
            editorRef.value.handleSave()
            break;
        case 'version':
            editorRef.value.saveVersionFun()
            break;
        default:
            break;
    }
}
function handleClose() {
    isShowArrow.value = false
    activeName.value = ''
    editorRef.value?.changeEditStatus(false)
}
function handleEvent(e: { keyCode: number; metaKey: any; ctrlKey: any; preventDefault: () => void }) {
    if (bodyLoading.value) return
    if (e.keyCode == 83 && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
        e.preventDefault();
        //为模板时 快捷键操作
        if (isTemplate.value) {
            createImg(docInfo.value)
        }
        return saveHandle()
    }
}
function saveHandle() {
    editorRef.value?.handleSave()
}
function createImg(item: any) {
    console.log(item)
}
function getCheckedFile(item: { knowledgeId: any; id: any }) {
    locationOther({
        id: docInfo.value.id,
        knowledgeId: item.knowledgeId || item.id,
        parentId: item.id
    }).then(res => {
        if (res.data.code == 0) {
            proxy.$onePrompt.$oneNotify({
                title: "提示",
                message: '移动文件成功',
                type: 'success',
                position: 'bottom-right',
            })
            init()
        }
    })
}
function changeArrow(value: boolean) {
    showButton.value = value
}
function openArrow() {
    showButton.value = false
}
function renderFinish() {
    bodyLoading.value = false
}
function changeLatelySave(val: any) {
    saveTime.value = proxy.$dayjs(val).format("HH:ss")
}
function endSwitchVersion(content: any, type: any) {
    editorRef.value?.changeVersionContent(content, type)
}
function changeEditStatus(val: any) {
    editorRef.value?.closeShortKey(val)
}
</script>
<style lang="scss" scoped>
.editor-page {
    width: 100%;
    // height: 100%;
    position: relative;

    .no-editor-mark {
        position: absolute;
        left: 0px;
        top: 0px;
        height: 100%;
        width: 100%;
        cursor: no-drop;
        margin-left: 60px;
    }

    // display: flex;
    // flex-direction: column !important;
    .ediotr-body {
        // height: calc(100vh - 48px);
        width: 100%;
        // aspect-ratio: 16/9;
        position: relative;
        display: flex;

        .editor-content {
            height: 100%;
            width: 100%;
            position: relative;
        }

        .fixed-button {
            position: fixed;
            top: 150px;
            right: 0px;
            z-index: 200;
            box-shadow: 0px 1px 10px 0px rgba(54, 59, 76, 0.15);
            width: 36px;
            height: 36px;
            border-radius: 4px 0px 0px 4px;
            overflow: hidden;
            cursor: pointer;

            .fixed-icon {
                width: 36px;
                height: 36px;
            }
        }
    }
}
</style>